import {
  delUserChannelsAPI,
  getAllChannelsAPI,
  getuserChannelsAPI,
  setUserChannelsAPI,
} from '@/api/channels';
import { hastoken, getLocalChannels, setLocalChannels } from '@/utils/storage';
import { AppDispatch } from '..';
import { channelsType, channlesAcrtionType } from '../reducer/channels';
// 获取所有频道列表
export const getAllChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getAllChannelsAPI();
    dispatch({ type: 'channel/savechannels', payload: res.data.channels });
  };
};
// 获取用户频道列表
export const getUserChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    if (hastoken()) {
      const res = await getuserChannelsAPI();
      dispatch({
        type: 'channel/saveUserChannels',
        payload: res.data.channels,
      });
    } else {
      const loalList = getLocalChannels();
      if (!!loalList.length) {
        dispatch({ type: 'channel/saveUserChannels', payload: loalList });
      } else {
        const res = await getAllChannelsAPI();
        // 1. 从缓存中取出时，无论长度，截取前10个
        const tenList = res.data.channels.slice(0, 10);
        dispatch({ type: 'channel/saveUserChannels', payload: tenList });
        // 2. 向缓存中同步为前10个
        setLocalChannels(tenList);
      }
    }
  };
};
// 2. 封装异步Action
export const setUserChannelAction = (newItem: channelsType) => {
  return async (dispatch: AppDispatch) => {
    // 3. 判断有无token，有token发请求。
    if (hastoken()) {
      await setUserChannelsAPI({ channels: [newItem] });
      dispatch({ type: 'channel/updateUserChannels', payload: newItem });
      return;
    }

    //4. 无token，删除缓存中的一条数据， 更新redux中的数据
    const localList = getLocalChannels();
    setLocalChannels([...localList, newItem]);
    dispatch({ type: 'channel/updateUserChannels', payload: newItem });
  };
};

export const delUserChannelAction = (id: number) => {
  return async (dispatch: AppDispatch) => {
    // 5.
    if (hastoken()) {
      await delUserChannelsAPI(id);
      dispatch({ type: 'channel/deletUserChannels', payload: id });
      return;
    }

    // 6.不存在token时，操作缓存
    const localList = getLocalChannels();
    setLocalChannels(localList.filter((v) => v.id !== id));
    dispatch({ type: 'channel/deletUserChannels', payload: id });
  };
};

export const setChannelIdAction = (id: number): channlesAcrtionType => {
  return {
    type: 'channel/setChannelId',
    payload: id,
  };
};
